<script setup lang="tsx">
import { ref, reactive, computed } from 'vue'
import { useGameStore } from '@/stores/modules/game'
import ChefImage from '@/components/ChefImage/index.vue'
import OptionView from './option.vue'
import type { DataTableColumns } from 'naive-ui'
import type { IChef } from '@/stores/types'

const chefs = useGameStore().chefs
const settings = ref({
  fixedDisplayColumn: ['galleryId', 'image', 'rarity'],
})

/** 通用列生成函数 */
function createColumns<T extends keyof IChef>(
  fields: ReadonlyArray<{ title: string; key: T }>,
): DataTableColumns<IChef> {
  return fields.map((field) => ({
    ...field,
    width: 60,
    align: 'center',
    render(row) {
      const value = row[field.key]
      return <>{value === 0 ? null : value}</>
    },
  }))
}

const techniquesColumns = createColumns([
  { title: '炒', key: 'stirfry' },
  { title: '煮', key: 'boil' },
  { title: '切', key: 'knife' },
  { title: '炸', key: 'fry' },
  { title: '烤', key: 'bake' },
  { title: '蒸', key: 'steam' },
] as const)

const collectColumns = createColumns([
  { title: '肉', key: 'meat' },
  { title: '面', key: 'creation' },
  { title: '菜', key: 'veg' },
  { title: '鱼', key: 'fish' },
] as const)

const condimentColumns = createColumns([
  { title: '甜', key: 'sweet' },
  { title: '酸', key: 'sour' },
  { title: '辣', key: 'spicy' },
  { title: '咸', key: 'salty' },
  { title: '苦', key: 'bitter' },
  { title: '鲜', key: 'tasty' },
] as const)

const columns = ref<DataTableColumns<IChef>>([
  {
    title: 'No.',
    key: 'galleryId',
    width: 60,
    align: 'center',
  },
  {
    title: '图',
    key: 'image',
    width: 70,
    align: 'center',
    render(row) {
      return <ChefImage id={row.chefId}></ChefImage>
    },
  },
  {
    title: '名字',
    key: 'name',
    width: 80,
    align: 'center',
    fixed: 'left',
  },
  {
    title: '星',
    key: 'rarity',
    width: 60,
    align: 'center',
  },
  ...techniquesColumns,
  ...collectColumns,
  ...condimentColumns,
])

const columnsComputed = computed(() => {
  const { fixedDisplayColumn } = settings.value
  return columns.value.filter((f) => {
    // 临时展示
    const keys = ['galleryId', 'image', 'rarity']
    if ('key' in f && typeof f.key === 'string') {
      if (!keys.includes(f.key)) {
        return true
      }
    }

    if ('key' in f && typeof f.key === 'string') {
      return fixedDisplayColumn.includes(f.key)
    }
    return false
  })
})

const tableWidth = computed(() =>
  columns.value.reduce((sum, col) => sum + Number(col?.width || 100), 0),
)

const pagination = reactive({
  pageSize: 8,
  showQuickJumper: true,
})
</script>

<template>
  <n-flex vertical :size="24">
    <OptionView :settings="settings" />
    <n-data-table
      :columns="columnsComputed"
      :data="chefs"
      :pagination="pagination"
      :single-line="false"
      size="small"
      :scroll-x="tableWidth"
    />
  </n-flex>
</template>

<style lang="scss" scoped></style>
